<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElLink, ElMessage, ElInput, ElDialog, ElMessageBox, ElSwitch } from 'element-plus'
import { Table } from '@/components/Table'
import { getTableListApi, identityExamineApi } from '@/api/course'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { formatToDateTime } from '@/utils/dateUtil'

type SelectOption = {
  label: string
  value: string
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await getTableListApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.records,
      total: res.data.total
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList } = tableMethods

const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}

const provinceList = ref<SelectOption[]>([])

const { t } = useI18n()

const crudSchemas = reactive<CrudSchema[]>([
  // {
  //   field: 'selection',
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     hidden: true
  //   },
  //   detail: {
  //     hidden: true
  //   },
  //   table: {
  //     type: 'selection'
  //   }
  // },
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    },
    detail: {
      hidden: true
    }
  },
  {
    field: 'title',
    label: '课程名称',
    search: {
      component: 'Input'
    },
    table: {
      slots: {
        default: (data: any) => {
          console.log(data, 'data')
          return (
            <ElLink underline={false} type={'primary'} onClick={() => action(data.row)}>
              {data.row.title}
            </ElLink>
          )
        }
      },
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'phone',
    label: '作者',
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'classifyName',
    label: '课程分类',
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'difficultyLevelName',
    label: '难度等级',
    search: {
      hidden: true
    },
    table: {
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'applicationTime',
    label: '创建时间',
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return <>{formatToDateTime(data.row.applicationTime)}</>
        }
      },
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'applicationTime',
    label: '是否推荐',
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <ElSwitch />
            </>
          )
        }
      },
      headerAlign: 'center',
      align: 'center'
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    search: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <div v-show={data.row.status === 0}>
                <BaseButton type="success" onClick={() => handlePass(data.row)}>
                  编辑
                </BaseButton>
                <BaseButton type="danger" onClick={() => clickReject(data.row)}>
                  删除
                </BaseButton>
              </div>
            </>
          )
        }
      },
      headerAlign: 'center',
      align: 'center'
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const rejectLoading = ref(false)
const identityVisible = ref(false)
const examineRow = ref<any>({})

const dialogVisible = ref(false)
const dialogTitle = ref('审核内容')

const currentRow = ref<any>(null)

const rejectReason = ref('')

const action = (row: any) => {
  if (!row.qualificationCert) {
    row.qualificationCert = []
  } else {
    row.qualificationCert = row.qualificationCert.join(',')
  }
  currentRow.value = row
  dialogVisible.value = true
}

const handlePass = async (row: any) => {
  ElMessageBox.confirm('是否确认审核通过?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const params: any = {
          id: row.id,
          status: 1
        }
        await identityExamineApi(params)
        ElMessage.success('已通过')
        getList()
      } catch (err) {
        ElMessage.error(err || '系统错误，请联系管理员')
      }
    })
    .catch(() => {})
}

const clickReject = async (row: any) => {
  examineRow.value = row
  identityVisible.value = true
}

const handleReject = async () => {
  try {
    const params: any = {
      id: examineRow.value.id,
      status: 2
    }
    await identityExamineApi(params)
    ElMessage.success('已通过')
    getList()
  } catch (err) {
    ElMessage.error(err || '系统错误，请联系管理员')
  }
}
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Detail :current-row="currentRow" />

    <template #footer>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
  <ElDialog
    v-model="identityVisible"
    title="请输入驳回理由"
    :close-on-click-modal="false"
    width="600px"
  >
    <ElInput
      v-model="rejectReason"
      :rows="8"
      maxlength="200"
      placeholder="请输入"
      show-word-limit
      type="textarea"
    />
    <template #footer>
      <BaseButton @click="identityVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      <BaseButton type="danger" :loading="rejectLoading" @click="handleReject"> 驳回 </BaseButton>
    </template>
  </ElDialog>
</template>
